import Store from "store";
import Router from "../bid/router/index";
import { getValid } from 'api/modules/bid.api';

// 判断当前时间是否已经超过需求时间
export const isReqOutTime = (date) => {
  const nowDate = new Date();
  const year = nowDate.getFullYear();
  const month =
    nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
  const day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
  const dateStr = year + "-" + month + "-" + day;
  return new Date(dateStr.replace(/-/g, "/")) > new Date(date.replace(/-/g, "/"));
};

// 根据id获取某一个需求
export const checkBidReqTime = () => {
  const data = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};
  Object.keys(data).forEach((item) => {
    data[item].data.forEach((e) => {
      if (e.status === 1 && isReqOutTime(e.timeReq)) {
        e.status = 2;
      }
    });
  });
  window.localStorage.setItem(DB_NAME, JSON.stringify(data));
};
const checkValid = () => {
  window.open("__blank", "notFound");
};
// 每30s检查一次需求是否到期
setInterval(() => {
  checkBidReqTime();
}, 10000);

setInterval(async () => {
  const { data, code } = await getValid();
  code !== 0 && Router.push('/unknown');
}, 60000);

// 数据库名称
const DB_NAME = "bid_require_list";

// status: 0 未发布 1 待投标

// 新建采购需求
export const addRequirement = (params) => {
  const list = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};
  // 给本地缓存新增数据
  const value = list[Store.state.userInfo.username]?.data || [];
  console.log("value", value);
  params.status = 0;
  value.push(params);
  list[Store.state.userInfo.username].data = value;
  window.localStorage.setItem(DB_NAME, JSON.stringify(list));
  console.log(list);
  return { code: 0, msg: "新建成功", data: {} };
};

// 删除未发布的采购需求
export const deleteRequirementPending = (ids) => {
  let code = 0;
  let msg = "获取成功";
  const data = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};

  const list = data[Store.state.userInfo.username] || [];

  list.data = list.data.filter((item) => {
    return !ids.includes(item.id);
  });
  window.localStorage.setItem(DB_NAME, JSON.stringify(data));
  return { code, data: true, msg };
};

// 获取未发布的采购需求
export const getRequirementPendingAll = () => {
  let code = 0;
  let msg = "获取成功";
  const data = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};

  const list = data[Store.state.userInfo.username] || [];

  const response = list.data.filter((item) => {
    return item.status === 0;
  });
  console.log(response);
  if (!response) {
    code = 500;
    msg = "暂无数据";
  }
  return { code, data: response, msg };
};

// 发布采购需求
export const publishRequirement = (params) => {
  let code = 0;
  let msg = "发布成功";
  // 获取需求列表
  const reqList = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};

  // 获取要发布的列表
  const list = reqList[Store.state.userInfo.username]?.data || [];

  let publishIds = [];
  params.forEach((item) => {
    publishIds.push(item.id);
  });

  console.log("publishIds", publishIds);

  list.forEach((item) => {
    if (publishIds.includes(item.id)) {
      item.status = 1;
      item.company = [];
      item.bidUser = [];
    }
  });

  reqList[Store.state.userInfo.username].data = list;
  window.localStorage.setItem(DB_NAME, JSON.stringify(reqList));
  return { code, data: {}, msg };
};

// 获取已发布的采购需求
export const getPublishRequirementAll = () => {
  let code = 0;
  let msg = "获取成功";
  const data = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};
  const { username, role, company } = Store.state.userInfo;

  const list = data[username] || [];

  let response = [];
  if (role === 0) {
    response = list.data.filter((item) => {
      return item.status > 0;
    });
    console.log(response);
    if (!response) {
      code = 500;
      msg = "暂无数据";
    }
  }

  if (role === 1) {
    Object.keys(data).forEach((item) => {
      const temp = data[item].data.filter((e) => {
        return e.bidUser === username;
      });
      response.push(...temp);
    });
  }

  return { code, data: response, msg };
};

// 获取已投标列表
export const getHasBidAll = () => {
  let code = 0;
  let msg = "获取成功";
  const data = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};

  let response = [];
  Object.keys(data).forEach((item) => {
    const temp = data[item].data.filter((e) => {
      return e.status >= 1 && e.company?.includes(Store.state.userInfo.company);
    });
    response.push(...temp);
  });

  console.log(response);
  if (!response) {
    code = 500;
    msg = "暂无数据";
  }
  return { code, data: response, msg };
};

// 获取待投标列表
export const getWaitBidAll = () => {
  let code = 0;
  let msg = "获取成功";
  const data = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};

  let response = [];
  Object.keys(data).forEach((item) => {
    const temp = data[item].data.filter((e) => {
      return e.status === 1 && !e.company?.includes(Store.state.userInfo.company);
    });
    response.push(...temp);
  });

  console.log(response);
  if (!response) {
    code = 500;
    msg = "暂无数据";
  }
  return { code, data: response, msg };
};

// 根据id获取某一个需求
export const getReqById = (id) => {
  let code = 0;
  let msg = "获取成功";
  const data = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};
  let req = {};
  Object.keys(data).forEach((item) => {
    const temp = data[item].data.filter((e) => {
      return e.id.toString() == id.toString();
    })[0];
    if (temp) {
      req = temp;
    }
  });
  console.log("req", req);
  if (!req) {
    code = 500;
    msg = "暂无数据";
  }
  return { code, data: req, msg };
};
// 去重
const banRepeat = (arr) => {
  const ARr = new Set();
  arr.forEach((v) => ARr.add(v));
  return [...ARr];
};
// 投标采购需求
export const bidRequirement = (params) => {
  let code = 0;
  let msg = "投标成功";
  // 获取需求列表
  const reqList = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};
  Object.keys(reqList).forEach((item) => {
    reqList[item].data.forEach((e) => {
      if (params.id === e.id) {
        e.status = 1;
        if (!(e.company instanceof Array)) {
          e.company = [];
        }
        if (!(e.bidUser instanceof Array)) {
          e.bidUser = [];
        }
        e.company.push(Store.state.userInfo.company);
        e.bidUser.push(Store.state.userInfo.username);
        e.company = banRepeat(e.company);
        e.bidUser = banRepeat(e.bidUser);
        e.fileList = {};
        e.fileList[Store.state.userInfo.company] = params.file;
      }
    });
  });
  window.localStorage.setItem(DB_NAME, JSON.stringify(reqList));
  return { code, data: {}, msg };
};

// 获取待评审列表
export const getWaitReviewAll = () => {
  let code = 0;
  let msg = "获取成功";
  const data = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};

  let response = [];
  Object.keys(data).forEach((item) => {
    const temp = data[item].data.filter((e) => {
      return e.status === 2;
    });
    response.push(...temp);
  });

  console.log(response);
  if (!response) {
    code = 500;
    msg = "暂无数据";
  }
  return { code, data: response, msg };
};

// 评审需求
export const reviewRequirement = (params) => {
  let code = 0;
  let msg = "评审成功";
  // 获取需求列表
  const reqList = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};
  Object.keys(reqList).forEach((item) => {
    reqList[item].data.forEach((e) => {
      if (params.id === e.id) {
        e.status = 3;
        e.reviewUser = Store.state.userInfo.username;
        e.expScore = params.expScore;
        e.executeScore = params.executeScore;
        e.bidPriceScore = params.bidPriceScore;
      }
    });
  });

  window.localStorage.setItem(DB_NAME, JSON.stringify(reqList));
  return { code, data: {}, msg };
};

// 中标需求
export const winBidRequirement = (params) => {
  let code = 0;
  let msg = "中标成功";
  // 获取需求列表
  const reqList = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};
  Object.keys(reqList).forEach((item) => {
    reqList[item].data.forEach((e) => {
      if (params.id === e.id) {
        e.status = 4;
        e.winBidUser = Store.state.userInfo.username;
        e.winBidCompany = Store.state.userInfo.company;
      }
    });
  });

  window.localStorage.setItem(DB_NAME, JSON.stringify(reqList));
  return { code, data: {}, msg };
};

// 获取中标列表
export const getWinBidListAll = () => {
  let code = 0;
  let msg = "获取成功";
  const data = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};

  const list = data[Store.state.userInfo.username] || [];
  const { role } = Store.state.userInfo;
  let response = null;
  if (role === 0) {
    response = list.data.filter((item) => {
      return item.status === 3;
    });
    console.log(response);
    if (!response) {
      code = 500;
      msg = "暂无数据";
    }
  }
  // 待开发先不动
  if (role === 1) {
    response = list.data.filter((item) => {
      return item.status === 3;
    });
    console.log(response);
    if (!response) {
      code = 500;
      msg = "暂无数据";
    }
  }

  return { code, data: response, msg };
};

// 获取已中标列表
export const getHasWinBidList = () => {
  let code = 0;
  let msg = "获取成功";
  const data = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};

  const list = data[Store.state.userInfo.username] || [];
  const { role } = Store.state.userInfo;
  let response = null;
  if (role === 0) {
    response = list.data.filter((item) => {
      return item.status === 4;
    });
    console.log(response);
    if (!response) {
      code = 500;
      msg = "暂无数据";
    }
  }
  // 待开发先不动
  if (role === 1) {
    response = list.data.filter((item) => {
      return item.status === 3;
    });
    console.log(response);
    if (!response) {
      code = 500;
      msg = "暂无数据";
    }
  }

  return { code, data: response, msg };
};
// 获取全部数据
export const getAllList = () => {
  let code = 0;
  let msg = "获取成功";
  const data = JSON.parse(window.localStorage.getItem(DB_NAME)) || {};
  const { username, role, company } = Store.state.userInfo;

  const list = data[username] || [];

  const arr = [];

  console.log("data", data);

  Object.keys(data).forEach((e) => {
    arr.push(...data[e].data);
  });

  let response = [];

  response = arr;
  console.log("getAllList", response);
  if (!response) {
    code = 500;
    msg = "暂无数据";
  }

  return { code, data: response, msg };
};
